package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"zy16/cache"
	"zy16/models"
)

type XinwenController struct {
	beego.Controller
}

func (c *XinwenController) Add() {
	num, _ := c.GetInt("num")
	title := c.GetString("title")
	types := c.GetString("types")

	xinwen := models.Xinwen{
		Num:   num,
		Title: title,
		Types: types,
	}
	err := models.DB.Debug().Create(&xinwen).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	marshal, _ := json.Marshal(xinwen)
	cache.Rdb.Set(cache.Ctx, "xinadd", marshal, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}
func (c *XinwenController) Update() {
	id, _ := c.GetInt("id")
	num, _ := c.GetInt("num")
	title := c.GetString("title")
	types := c.GetString("types")
	xinwen := models.Xinwen{
		Num:   num,
		Title: title,
		Types: types,
	}
	err := models.DB.Debug().Where("id=?", id).Updates(&xinwen).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}

	marshal, _ := json.Marshal(xinwen)
	cache.Rdb.Set(cache.Ctx, "xinupdate", marshal, 0)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
func (c *XinwenController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Xinwen{}, id).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	var xinwen models.Xinwen
	marshal, _ := json.Marshal(xinwen)
	cache.Rdb.Set(cache.Ctx, "xindel", marshal, 0)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
func (c *XinwenController) List() {
	var xin []models.Xinwen
	get, _ := cache.Rdb.Get(cache.Ctx, "xinlist").Result()
	if get != "" {
		json.Unmarshal([]byte(get), &xin)
	} else {
		models.DB.Find(&xin)
		marshal, _ := json.Marshal(xin)
		cache.Rdb.Set(cache.Ctx, "xinlist", marshal, 0)
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "展示成功",
		"data": xin,
	}
	c.ServeJSON()
	return
}
